package javango.contrib.jquery;

import com.google.inject.Binder;
import com.google.inject.Inject;

import javango.api.Settings;
import javango.contrib.jquery.widgets.JQueryDateTimeWidget;
import javango.contrib.jquery.widgets.JQueryDateWidget;
import javango.contrib.jquery.widgets.JQuerySelectWidget;
import javango.forms.Form;
import javango.forms.fields.BoundField;

public class Helper {

	/**
	 * full path and file name to the property that has the jquery java script include.
	 */
	public final static String JQUERY_JS = "jquery_js";
	
	/**
	 * full path and file name to the property that has the jquery css include
	 */
	public final static String JQUERY_CSS = "jquery_css";
	
	protected Form form;
	protected Settings settings;
	protected String basePath;

	@Inject
	public Helper(Settings settings) {//, String basePath) {
		this.settings = settings;
//		this.basePath = basePath;
	}
	
	public Helper forForm(Form form) {
		this.form = form;
		return this;
	}

	public String getHeader() {
		StringBuilder b = new StringBuilder();
		// TODO Allow for JS, CSS to be relative to this app or absolute)  ie if they start with a / do not prepend basePath.
		//  make a helper function for widgets can perform this check as well,  ie jqueryselectwidget.
		// TODO better way to allow this to be specified,  ie if they need the IE logic
		if (settings.get(JQUERY_JS) != null) {
			b.append(String.format("<script src='%s' type='text/javascript'></script>\n", settings.get(JQUERY_JS)));
		}
		if (settings.get(JQUERY_CSS) != null) {
			b.append(String.format("<link rel='stylesheet' type='text/css' href='%s'/>\n", settings.get(JQUERY_CSS)));		
		}
				
		return b.toString();
	}
	
	public String getScript() {
		StringBuilder value = new StringBuilder();
		// returns the jquery script for all fields in the form.
		
		for (BoundField boundField:form) {
			if (boundField.getWidget() instanceof JqueryWidget) {
				JqueryWidget jqWidget = (JqueryWidget)boundField.getWidget();
				// TODO allow getScrpipt to return null and ignore those results.
				value.append(jqWidget.getScript(boundField));
				value.append("\n"); // TODO add this only on debug??
			}
		}
		
		if (value.length() != 0) {
			// TODO is this the correct way to run post page load??
			value.insert(0,"jQuery(function($){");
			value.append("});");
			return value.toString();
		}
		return "";
	}
	
	public static void bind(Binder binder) {
		binder.bind(javango.forms.widgets.SelectWidget.class).to(JQuerySelectWidget.class);
		binder.bind(javango.forms.widgets.DateWidget.class).to(JQueryDateWidget.class);
		binder.bind(javango.forms.widgets.DateTimeWidget.class).to(JQueryDateTimeWidget.class);
	}

	public String getBasePath() {
		return basePath;
	}

	public Helper setBasePath(String basePath) {
		this.basePath = basePath;
		return this;
	}
}
